package main

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"time"
)

type MySqlConfig struct{
	Host string `mapstructure:"host"`
	Port string `mapstructure:"port"`
}

type ServerConfig struct {
	Name string `mapstructure:"name"`
	MySQLInfo MySqlConfig`mapstructure:"mysql"`
}

func GetEnvInfo(key string) bool {
	viper.AutomaticEnv()
	return viper.GetBool(key)
}

func main() {
	isDebug := GetEnvInfo("DEBUG")
	configPrefix := "config"
	fileName := fmt.Sprintf("viper_test/ch02/%s-pro.yaml", configPrefix)
	if isDebug {
		fileName = fmt.Sprintf("viper_test/ch02/%s-debug.yaml", configPrefix)
	}


	v := viper.New()
	// 文件路径如何设置
	v.SetConfigFile(fileName)
	if err := v.ReadInConfig(); err != nil {
		panic(err)
	}
	// 直接获取一个配置
	//fmt.Println(v.Get("name"))

	// 批量获取配置
	srvCfg := ServerConfig{}
	if err := v.Unmarshal(&srvCfg); err != nil {
		panic(err)
	}
	fmt.Println(srvCfg)

	// 动态监控文件的变化
	v.WatchConfig()
	v.OnConfigChange(func (e fsnotify.Event){
		fmt.Println("Config file changed", e.Name)
		_ = v.ReadInConfig()
		_ = v.Unmarshal(&srvCfg)
		fmt.Println(srvCfg)
	})

	time.Sleep(time.Second * 300)
}